package com.lanzhou.yuanfen.config;


import com.lanzhou.yuanfen.sys.entity.User;
import com.lanzhou.yuanfen.util.RequestUtil;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 登入的时候需要将用户名注入进来
 *
 * @author Administrator
 */
@Component
public class IpAddressContext {

    /**
     * Address地址: key: ip value: username
     */
    private Map<String, String> address = new HashMap<>();

    /**
     * 添加IP
     *
     * @param ip
     */
    public void putAddress(String ip) {
        address.put(ip, ip);
    }

    /**
     * 更新IP, 一般是登入后
     *
     * @param request
     */
    public void updateAddress(HttpServletRequest request) {
        String ipAddress = RequestUtil.getIpAddress(request);
        User userInfo = Token.getUserInfo();
        if (userInfo == null) {
            updateAddress(ipAddress, ipAddress);
        }
        updateAddress(ipAddress, userInfo.getUsername());
    }


    /**
     * 更新IP, 一般是登入后
     *
     * @param ip
     * @param username
     */
    private void updateAddress(String ip, String username) {
        address.put(ip, username);
    }

    /**
     * 重写这个用于 onAuthenticationSuccess
     *
     * @param request
     * @param user
     */
    public void updateAddress(HttpServletRequest request, User user) {
        String ipAddress = RequestUtil.getIpAddress(request);
        updateAddress(ipAddress, user.getUsername());
    }

    /**
     * 获取Ip
     *
     * @param ip
     * @return
     */
    public String getAddress(String ip) {
        return address.get(ip);
    }

    /**
     * 删除Ip
     *
     * @param ip
     */
    public void removeAddress(String ip) {
        address.remove(ip);
    }

    /**
     * 清空Ip
     */
    public void clearAddress() {
        address = new HashMap<>();
    }


    public Map<String, String> getAddress() {
        return address;
    }

}
